/*  
 * cafe-gistools.js
 * @Author :      GUORUI
 * @CreateDate :  2017年6月23日
 * Copyright (c) 2017, NRIET.　
 * 日期控件
 */

;define(function(){
	/**
	 * 创建控件界面
	 */
	function getNodeHtml(cfg){
		var wrapper = $('<div class="gistools">'),
			tools = $('<div class="gistools-title">');
		tools.append($('<i>').addClass("gistools-title-"+cfg.type+"-icon")).append($('<span>').text(cfg.name));
		wrapper.append(tools);
		$.each(gisTools[cfg.type],function(){
			var t = $('<div class="tools-icon">');
			t.addClass(this.icon).attr({"title":this.name,"id":"gistools-"+this.id}).hide();
			wrapper.append(t);
		});
		return wrapper;
	}
	/**
	 * 绑定事件
	 */
	function _eves($drop,cfg){
		$drop.undelegate().delegate(".gistools-title","click",function(){
			if($(this).hasClass("active")){
				$(this).removeClass("active");
				$(this).siblings().hide();
			}else{
				$(this).addClass("active");
				$(this).siblings().show();
			}
		}).delegate(".tools-icon","click",function(event){
			event.stopPropagation();
			if(!$(this).hasClass("disabled")){
				if(cfg.type == "draw"){			//绘制工具
					$(this).siblings(".tools-icon").removeClass("active");
					if($(this).hasClass("active")){
						$(this).removeClass("active");
					}else{
						$(this).addClass("active");
					}
					callGisFun($drop,$(this).attr("id"),$(this).hasClass("active"),cfg);
				}else if(cfg.type == "gis"){
					//兄弟节点
					var $oldIcon = $(this).siblings(".tools-icon").filter(".active");
					$oldIcon.removeClass("active");
					clearGisIcon($oldIcon,cfg);
					//自己
					if($(this).hasClass("active")){
						$(this).removeClass("active");
						clearGisIcon($(this),cfg);
					}else{
						$(this).addClass("active");
						gisIconCall($drop,$(this).attr("id"),cfg);
					}
				}else if(cfg.type == "gzq"){
					var id = $(this).attr("id");
					if(id.endsWith("drawgzq")){	//绘制关注区
						var obj = $(this).siblings(".tools-icon[id$=xsgzq]");
						if(obj.hasClass("active")){
							obj.removeClass("active");
							clearGisIcon(obj,cfg);
						}
					}else if(id.endsWith("xsgzq")){	//显示关注区
						var obj = $(this).siblings(".tools-icon[id$=drawgzq]");
						if(obj.hasClass("active")){
							obj.removeClass("active");
							clearGisIcon(obj,cfg);
						}
					}
					//自己
					if($(this).hasClass("active")){
						$(this).removeClass("active");
						clearGisIcon($(this),cfg);
					}else{
						$(this).addClass("active");
						gzqGis($drop,$(this).attr("id"),cfg);
					}
				}
			}
		});
		
		$(document).on('keydown',function(ev){
			if(27 == ev.keyCode){
				var drawType = $drop.data("gt-draw-type");
				var drawStatus = $drop.data("gt-draw-status");
				if(0 == drawType){//基于落区
					if("add" == drawStatus){
						
					}else if("edit" == drawStatus){
						
					}
				}else{//基于行政区
					if("add" == drawStatus){
						
					}else if("edit" == drawStatus){
						
					}
				}
			}
		});
		
		$(top.document).on('keydown',function(ev){
			if(27 == ev.keyCode){
				var drawType = $drop.data("gt-draw-type");
				var drawStatus = $drop.data("gt-draw-status");
			}
		});
	}
	
	/**
	 * 关注区方法
	 */
	function gzqGis($drop,id,cfg){
		var symbol={
			"stroke":'rgb(118, 87, 239)',
			"fill":'rgba(118, 87, 239,0.4)',
			"fill-opacity":"0.5",
			"stroke-dasharray":"10,10"
		};
		var layerId = "circleLayer";	//关注区图层--绘制和显示的图层
		var layerId1 = "buffer30";
		var layerId2 = "buffer50";
		
		if(id.endsWith("drawgzq")){				//关注区绘制
			GIS.Draw.startDraw(cfg.gisId,layerId,"circle",null,symbol,function(graphic){
				GIS.Draw.endDraw(cfg.gisId,layerId);
				var geometry = graphic.geometry;
				var edgePoint = graphic.edgePoint;
				
				if($.isArray(geometry) && $.isArray(edgePoint) && geometry.length==2 && edgePoint.length==2){
					var center = geometry.join(",");
					var boundary = edgePoint.join(",");
					
					informWin.showWin({
						"info" : "是否保存关注区！",
						"btns" : [
						          {
						        	  "name" : "确定",
						        	  "trigger" : "cancel",
						        	  "callBack" : function(){
						        		  if($.isFunction(cfg.call)){
						        			  cfg.call({
						        				  gisId:cfg.gisId,
						        				  layerId:layerId,
						        				  type:id,
						        				  info:{
						        					  center : center, 
						        					  boundary : boundary
						        				  }
						        			  })
						        		  }
						        	  }
						          },
						          {
						        	  "name" : "取消",
						        	  "trigger" : "cancel",
						        	  "callBack" : function(){
						        		  $drop.find("div[id$=drawgzq]").removeClass("active");
						        		  GIS.LayerControll.deleteLayer(cfg.gisId,layerId);
						        	  }
						          },
						          ],
					},function(data){});
				}
			});
		}else if(id.endsWith("xsgzq")){			//显示关注区
			  if($.isFunction(cfg.call)){
				 cfg.call({
					 gisId:cfg.gisId,
					 layerId:layerId,
					 type:id,
					 symbol:symbol
				 })
			  }
		}else if(id.endsWith("30km")){			//30公里
			symbol["fill-opacity"] = "0";
			symbol["stroke-width"] = "2";
			GIS.Graphic.showBuferr(cfg.gisId,layerId1,{
				areacode:user.codeId,
				filename:"buffer_30",
				symbol:symbol
			});
		}else if(id.endsWith("50km")){			//50公里
			symbol["fill-opacity"] = "0";
			symbol["stroke-width"] = "2";
			GIS.Graphic.showBuferr(cfg.gisId,layerId2,{
				areacode:user.codeId,
				filename:"buffer_50",
				symbol:symbol
			});
		}
	}
	
	/**
	 * gis工具方法
	 */
	function gisIconCall($drop,id,cfg){
		if(id.endsWith("mj")){//面积
			GIS.Measure({
				id:"gt-gis-mj",
				type:"area",
				status : "start",
				GLMap:mapObj[cfg.gisId]
			});
		}else if(id.endsWith("jl")){//距离
			GIS.Measure({
				id:"gt-gis-jl",
				type:"distance",
				status :"start",
				GLMap:mapObj[cfg.gisId]
			});
		}else if(id.endsWith("my")){//漫游
			GLMap.enablePan();
		}else if(id.endsWith("tc")){//图层
			
		}
	}
	
	/**
	 * gis方法清除操作  
	 */
	function clearGisIcon($oldIcon,cfg){
		$oldIcon.each(function(){
			var id = $(this).attr("id");
			if(id.endsWith("mj")){			//面积
				GIS.Measure({
					id:"gt-gis-mj",
					type:"area",
					status : "stop",
					GLMap:mapObj[cfg.gisId]
				});
			}else if(id.endsWith("jl")){	//距离
				GIS.Measure({
					id:"gt-gis-jl",
					type:"distance",
					status : "stop",
					GLMap:mapObj[cfg.gisId]
				});
			}else if(id.endsWith("my")){	//漫游
				GLMap.disablePan();
			}else if(id.endsWith("tc")){	//图层
				
			}else if(id.endsWith("30km")){	//30km
				GIS.LayerControll.deleteLayer(cfg.gisId,"buffer30");
			}else if(id.endsWith("50km")){	//50km
				GIS.LayerControll.deleteLayer(cfg.gisId,"buffer50");
			}else if(id.endsWith("drawgzq")){	//绘制关注区
				GIS.LayerControll.deleteLayer(cfg.gisId,"circleLayer");
			}else if(id.endsWith("xsgzq")){	//显示关注区
				GIS.Draw.endDraw(cfg.gisId,"circleLayer");
				GIS.LayerControll.deleteLayer(cfg.gisId,"circleLayer");
			}
			
		})
	}
	
	/**
	 * 调用GIS方法(绘制工具-预警信号制作)
	 */
	function callGisFun($drop,id,isSelected,cfg){
		if(id.endsWith("lq")){//基于落区
			if(isSelected){
				//清除之前操作
				clearState($drop,cfg);
				if(0 == $drop.data("gt-draw-type")){
					GIS.LayerControll.deleteLayer(cfg.gisId,cfg.layerId);
				}
				$drop.data("gt-draw-type",1);
				$drop.data("gt-draw-status","add");
				GIS.Draw.selectRegions(cfg.gisId,[cfg.layerId],cfg.baseDataUrl,
					{
						supernames : cfg.supernames,
						bShowRegion : false,
						polygonStyle : cfg.getStyle(),
						makeType : cfg.getMakeType(),
						call:function(result,layerId,reGra){
							$drop.removeData("gt-draw-status");
							$drop.find(".tools-icon[id='"+id+"']").removeClass("active");
							$drop.find(".tools-icon[id='gistools-xzq']").addClass("disabled");
							$drop.find(".tools-icon[id='gistools-edit']").removeClass("disabled");
							$drop.find(".tools-icon[id='gistools-clear']").removeClass("disabled");
							GIS.Draw.endDraw(cfg.gisId,cfg.layerId);
							GIS.Graphic.highlight(cfg.gisId,cfg.layerId,{"strokeStyle" : "rgb(0, 0, 0)", "lineWidth" : 2},true);
							if($.isFunction(cfg.call)){
								cfg.call({type:"lq",data:result,layerId:layerId,reGra:reGra});
							}
						}
					}
				);
			}else{
				$drop.removeData("gt-draw-type");
				$drop.removeData("gt-draw-status");
				GIS.Draw.endDraw(cfg.gisId,cfg.layerId);
			}
		}else if(id.endsWith("xzq")){//基于行政区
			if(isSelected){
				//清除之前操作
				clearState($drop,cfg);
				if(1 == $drop.data("gt-draw-type")){
					GIS.LayerControll.deleteLayer(cfg.gisId,cfg.layerId);
				}
				$drop.data("gt-draw-type",0);
				$drop.data("gt-draw-status","add");
				var style = cfg.getStyle();
				style.bUnion = true;
				GIS.Draw.selectRegions(cfg.gisId,["gt-draw-temp",cfg.layerId],cfg.baseDataUrl,
					{
						supernames : cfg.supernames,
						bShowRegion : true,
						regionStyle : style,
						makeType : cfg.getMakeType(),
						call:function(result,layerId,reGra){
							$drop.removeData("gt-draw-status");
							$drop.data("gt-draw-xzq-groupId",reGra.id);
							$drop.find(".tools-icon[id='"+id+"']").removeClass("active");
							$drop.find(".tools-icon[id='gistools-lq']").addClass("disabled");
							$drop.find(".tools-icon[id='gistools-edit']").removeClass("disabled");
							$drop.find(".tools-icon[id='gistools-del']").removeClass("disabled");
							$drop.find(".tools-icon[id='gistools-clear']").removeClass("disabled");
							GIS.Draw.endDraw(cfg.gisId,"gt-draw-temp");
							GIS.Graphic.highlight(cfg.gisId,cfg.layerId,{"strokeStyle" : "rgb(0, 0, 0)", "lineWidth" : 2},true);
							if($.isFunction(cfg.call)){
								cfg.call({type:"xzq",data:result,layerId:layerId,reGra:reGra});
							}
						}
					}
				);
			}else{
				$drop.removeData("gt-draw-type");
				$drop.removeData("gt-draw-status");
				GIS.Draw.endDraw(cfg.gisId,"gt-draw-temp");
			}
		}else if(id.endsWith("edit")){//编辑
			var drawType = $drop.data("gt-draw-type");
			if(1 == drawType){//基于落区编辑
				if(isSelected){
					//清除之前操作
					clearState($drop,cfg);
					$drop.data("gt-draw-status","edit");
					GIS.Edit.startEdit(cfg.gisId,[cfg.layerId],{call:function(graphic,data){
						var d = GIS.Select.polygons(cfg.gisId,GLMap.geometryData.areaconfig,graphic,{supernames : cfg.supernames});
						if($.isFunction(cfg.call)){
							cfg.call({type:"lq-edit",data:d,layerId:cfg.layerId,reGra:data});
						}
					},editNum:1});
				}else{
					$drop.removeData("gt-draw-status");
					GIS.Edit.endEdit(cfg.gisId,[cfg.layerId]);
				}
			}else{//基于行政区编辑
				if(isSelected){
					//清除之前操作
					clearState($drop,cfg);
					$drop.data("gt-draw-status","edit");
					GIS.Draw.selectRegions(cfg.gisId,["gt-draw-temp",cfg.layerId],cfg.baseDataUrl,
						{
							supernames : cfg.supernames,
							bPick : true,
							groupId : $drop.data("gt-draw-xzq-groupId"),
							call:function(result,layerId,reGra,cs){
								if($.isFunction(cfg.call)){
									cfg.call({type:"xzq-edit",layerId:layerId,data:result,reGra:reGra});
								}
							}
						}
					);
				}else{
					$drop.removeData("gt-draw-status");
					GIS.Draw.endDraw(cfg.gisId,"gt-draw-temp");
				}
			}
		}else if(id.endsWith("del")){//删除单个行政区
			if(isSelected){
				//清除之前操作
				clearState($drop,cfg);
				$drop.data("gt-draw-status","del");
				GIS.Edit.setState(cfg.gisId,cfg.layerId,"deleting",true,function(result,layerId,reGra){
					if(0 == result.length){
						$drop.removeData("gt-draw-xzq-groupId");
						$drop.removeData("gt-draw-status");
						GIS.Edit.setState(cfg.gisId,cfg.layerId,"deleting",false);
						$drop.find(".tools-icon[id='"+id+"']").removeClass("active").addClass("disabled");
						$drop.find(".tools-icon[id='gistools-lq']").removeClass("disabled");
						$drop.find(".tools-icon[id='gistools-edit']").addClass("disabled");
						$drop.find(".tools-icon[id='gistools-clear']").addClass("disabled");
					}
					
					if($.isFunction(cfg.call)){
						cfg.call({type:"xzq-del",layerId:layerId,data:result,reGra:reGra});
					}
				});
			}else{
				$drop.removeData("gt-draw-status");
				GIS.Edit.setState(cfg.gisId,cfg.layerId,"deleting",false);
			}
		}else if(id.endsWith("clear")){//删除
			var drawType = $drop.data("gt-draw-type");
			if(1 == drawType){//基于落区删除
				if(isSelected){
					//清除之前操作
					clearState($drop,cfg);
					$drop.data("gt-draw-status","clear");
					GIS.Edit.setState(cfg.gisId,cfg.layerId,"deleting",true,function(reGra,delNum){
						if(0 == delNum){
							$drop.removeData("gt-draw-status");
							GIS.Edit.setState(cfg.gisId,cfg.layerId,"deleting",false);
							$drop.find(".tools-icon[id='"+id+"']").removeClass("active").addClass("disabled");
							$drop.find(".tools-icon[id='gistools-xzq']").removeClass("disabled");
							$drop.find(".tools-icon[id='gistools-edit']").addClass("disabled");
							//还原致原始图层
							cfg.layerId = "draw-gis-map";
						}
						
						if($.isFunction(cfg.call)){
							cfg.call({type:"lq-clear",reGra:reGra});
						}
					});
				}else{
					$drop.removeData("gt-draw-status");
					GIS.Edit.setState(cfg.gisId,cfg.layerId,"deleting",false);
				}
			}else{//基于行政区删除
				if(isSelected){
					//清除之前操作
					clearState($drop,cfg);
					$drop.data("gt-draw-status","clear");
					GIS.Edit.setState(cfg.gisId,cfg.layerId,"multideleting",true,function(result,layerId,reGra,gNum){
						if(0 == gNum){
							$drop.removeData("gt-draw-status");
							GIS.Edit.setState(cfg.gisId,cfg.layerId,"multideleting",false);
							$drop.find(".tools-icon[id='"+id+"']").removeClass("active").addClass("disabled");
							$drop.find(".tools-icon[id='gistools-lq']").removeClass("disabled");
							$drop.find(".tools-icon[id='gistools-edit']").addClass("disabled");
							$drop.find(".tools-icon[id='gistools-del']").addClass("disabled");
							//清除图层
							GIS.LayerControll.deleteLayer(CafeJS.DL_MAIN.dlGisId,layerId);
							//还原致原始图层
							cfg.layerId = "draw-gis-map";
						}
						
						if($.isFunction(cfg.call)){
							cfg.call({type:"xzq-clear",reGra:reGra});
						}
					});
				}else{
					$drop.removeData("gt-draw-status");
					GIS.Edit.setState(cfg.gisId,cfg.layerId,"multideleting",false);
				}
			}
		}
	}
	//清除之前操作
	function clearState($drop,cfg){
		var drawType = $drop.data("gt-draw-type");
		var drawStatus = $drop.data("gt-draw-status");
		if(1 == drawType){//基于落区
			if("add" == drawStatus){
				GIS.Draw.endDraw(cfg.gisId,cfg.layerId);
			}else if("edit" == drawStatus){
				GIS.Edit.endEdit(cfg.gisId,[cfg.layerId]);
			}else if("clear" == drawStatus){
				GIS.Edit.setState(cfg.gisId,cfg.layerId,"deleting",false);
			}
		}else{//基于行政区
			if("add" == drawStatus || "edit" == drawStatus){
				GIS.Draw.endDraw(cfg.gisId,"gt-draw-temp");
			}else if("del" == drawStatus){
				GIS.Edit.setState(cfg.gisId,cfg.layerId,"deleting",false);
			}else if("clear" == drawStatus){
				GIS.Edit.setState(cfg.gisId,cfg.layerId,"multideleting",false);
			}
		}
	}
	var gisTools = {
		 gis : [
	        {id:"jl",name : "距离",icon : "gistools-jl-icon"},
	        {id:"mj",name : "面积",icon : "gistools-mj-icon"},
	        {id:"my",name : "漫游",icon : "gistools-my-icon"},
	        {id:"tc",name : "图层",icon : "gistools-tc-icon"}
	     ],
		 draw : [
	        {id:"lq",name : "绘制落区",icon : "gistools-zx-icon"},
	        {id:"xzq",name : "绘制行政区",icon : "gistools-jyxzq-icon"},
	        {id:"edit",name : "编辑",icon : "gistools-bj-icon disabled"},
	        {id:"del",name : "删除单个行政区",icon : "gistools-scxzq-icon disabled"},
	        {id:"clear",name : "删除",icon : "gistools-sc-icon disabled"}
	     ],
	     gzq : [
            {id:"30km",name : "30km",icon : "gistools-30km-icon"},
            {id:"50km",name : "50km",icon : "gistools-50km-icon"},
            {id:"drawgzq",name : "绘制关注区",icon : "gistools-drawgzq-icon"},
            {id:"xsgzq",name : "显示关注区",icon : "gistools-xsgzq-icon"},
         ]
	};
	/**
	 * 控件构造函数
	 */
	var CFGistools = function(settings){
		var options = {
			baseDataUrl : '' ,//Gis文件路径
			appendTo: '',//控件所在容器
			name : null,//工具名称
			type : null,//工具类型
			gisId : null,//GIS地图的id
			supernames : ["宁波市"],
			layerId : "draw-gis-map",//图层Id
			call : null,//GIS操作完成后的回调函数
			getStyle : function(){//获取样式
				return {fillStyle:"rgb(0,0,255)",strokeStyle:"rgb(0,0,255)"}
			},
			getMakeType : null	//获取制作类型（全市预警、预警信号）
		};
		this.config = $.extend({},options, settings);
		this.$drop = getNodeHtml(this.config);
		_eves(this.$drop,this.config);
		if(this.config.appendTo){
			$(this.config.appendTo).append(this.$drop);
		}
	}
	/**
	 * 控件对外提供的方法
	 */
	CFGistools.prototype = {
		disabled : function(){
			clearState(this.$drop,this.config);
			this.$drop.removeData("gt-draw-status");
			this.$drop.removeData("gt-draw-type");
			this.$drop.removeData("gt-draw-xzq-groupId");
			this.$drop.find("div.tools-icon").removeClass("active").addClass("disabled");
		},
		active : function(){
			this.$drop.removeData("gt-draw-status");
			this.$drop.removeData("gt-draw-type");
			this.$drop.removeData("gt-draw-xzq-groupId");
			this.config.layerId = "draw-gis-map";
			this.$drop.find("div.tools-icon:lt(2)").removeClass("disabled active").last().nextAll().removeClass("active").addClass("disabled");
			GIS.Draw.endDraw(this.config.gisId,this.config.layerId);
			GIS.Edit.endEdit(this.config.gisId,[this.config.layerId]);
		},
		setBtnState : function(opt){
			this.config = $.extend(this.config,opt);
			this.$drop.data("gt-draw-type",opt.isAreaDraw);
			if(0 == opt.isAreaDraw){
				this.$drop.data("gt-draw-xzq-groupId",opt.groupId);
			}
			for(var i = 0; i < opt.ids.length; i++){
				this.$drop.find("div.tools-icon[id='gistools-"+opt.ids[i]+"']").removeClass("disabled");
			}
		},
		initDrawTool : function(id){
			this.$drop.find("div.tools-icon:lt(2)").removeClass("disabled active").last().nextAll().addClass("disabled");
			var $drawTool = this.$drop.find(".gistools-title");
			if(!$drawTool.hasClass("active")){
				$drawTool.click();
			}
			this.$drop.find("div.tools-icon[id='gistools-"+id+"']").addClass("active");
		},
		setDrawState : function(isActive){
			var $drawIcon = this.$drop.find("div.tools-icon.active");
			if($drawIcon.hasClass("active")){
				var id = $drawIcon.attr("id");
				callGisFun(this.$drop,id,isActive,this.config);
			}
		},
		upConfig : function(opt){
			this.config = $.extend(this.config, opt);
		}
	};
	
	CafeJS.Gistools = function(settings){
		var drop = new CFGistools(settings);
		return drop;
	}
});